package com.wwm.findit;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.Holder;
import com.orhanobut.dialogplus.OnCancelListener;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;


public class ObjectActivity extends Activity
{

	private EditText editTextItemName;
	private EditText editTextLevel;
	private EditText editTextItemAmount;
	private EditText editTextItemValue;
	private EditText editTextTip1;
	private EditText editTextTip2;
	private EditText editTextTip3;
	private EditText editTextMsg;

	private String itemLevel;
	private String md5;

	private RequestQueue mRequestQueue;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_object);

		editTextItemName = (EditText) findViewById(R.id.edittext_object_name);
		editTextItemAmount = (EditText) findViewById(R.id.edittext_count);
		editTextItemValue = (EditText) findViewById(R.id.edittext_price);
		editTextTip1 = (EditText) findViewById(R.id.edittext_tip1);
		editTextTip2 = (EditText) findViewById(R.id.edittext_tip2);
		editTextTip3 = (EditText) findViewById(R.id.edittext_tip3);
		editTextMsg = (EditText) findViewById(R.id.edittext_msg);
		editTextLevel = (EditText) findViewById(R.id.edittext_level);


		Button btn_ok = (Button) findViewById(R.id.button_ok);
		btn_ok.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				String key = GlobalData.username + System.currentTimeMillis();
				md5 = md5(key);
				Log.i("FindIt", key + ":" + md5);

				itemLevel = editTextLevel.getText().toString();

				if (GlobalData.userLevel < Integer.parseInt(itemLevel))
				{
					Toast.makeText(ObjectActivity.this, "物品等级不能高于用户等级", Toast.LENGTH_SHORT).show();
					return ;
				}

				//showQRCodeDialog(DialogPlus.Gravity.CENTER, md5);

				mRequestQueue = Volley.newRequestQueue(v.getContext());
				Map<String, String> map = new HashMap<String, String>();
				map.put("md5", md5);
				map.put("username", GlobalData.username);
				map.put("objectname", editTextItemName.getText().toString());
				map.put("level", itemLevel);
				map.put("tip_one", editTextTip1.getText().toString());
				map.put("tip_two", editTextTip2.getText().toString());
				map.put("tip_three", editTextTip3.getText().toString());
				map.put("msg", editTextMsg.getText().toString());
				map.put("value", editTextItemValue.getText().toString());
				map.put("number", editTextItemAmount.getText().toString());

				int value = Integer.parseInt(editTextItemValue.getText().toString());
				int number = Integer.parseInt(editTextItemAmount.getText().toString());

				if (GlobalData.userWealth < value * number)
				{
					Toast.makeText(ObjectActivity.this, "您的财富值不足", Toast.LENGTH_SHORT).show();
					return ;
				}

				GlobalData.userWealth -= value * number;

				/*
				*  $md5= $obj->{'md5'};
				$username = $obj->{'username'};
			$level = (int)$obj->{'level'};
			$tip_one = $obj->{'tip_one'};
			$tip_two= $obj->{'tip_two'};
			$tip_three= $obj->{'tip_three'};
			$msg = $obj->{'msg'};
			$value = (double)($obj->{'value'});
			$num = (int)($obj->{'number'});
				* */

				JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.UPLOAD_ITEM_BASIC_INFO_URL, new JSONObject(map), new Response.Listener<JSONObject>()
				{
					@Override
					public void onResponse(JSONObject response)
					{
						Log.i("FindIt", response.toString());
						try
						{
							int retCode = response.getInt("success");
							if (retCode == 0)
							{
								Toast.makeText(ObjectActivity.this, "生成物品成功", Toast.LENGTH_SHORT).show();
								showQRCodeDialog(DialogPlus.Gravity.CENTER, md5);
							}
							else
							{
								Toast.makeText(ObjectActivity.this, "生成物品失败:" + response.getString("message"), Toast.LENGTH_SHORT).show();
								return ;
							}
						} catch (JSONException e)
						{
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener()
				{
					@Override
					public void onErrorResponse(VolleyError error)
					{
						Log.i("FindIt", error.getMessage());
					}
				});
				mRequestQueue.add(jr);
			}
		});

		Button btn_cancel = (Button) findViewById(R.id.button_cancel);
		btn_cancel.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				ObjectActivity.this.finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_object, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		//noinspection SimplifiableIfStatement
		if (id == R.id.action_settings)
		{
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	public void createQRImage(String url, ImageView view)
	{

		try
		{
			if (url == null || "".equals(url) || url.length() < 1)
			{
				return;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			//图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, GlobalData.QR_WIDTH, GlobalData.QR_HEIGHT, hints);
			int[] pixels = new int[GlobalData.QR_WIDTH * GlobalData.QR_HEIGHT];
			//下面这里按照二维码的算法，逐个生成二维码的图片，
			//两个for循环是图片横列扫描的结果
			for (int y = 0; y < GlobalData.QR_HEIGHT; y++)
			{
				for (int x = 0; x < GlobalData.QR_WIDTH; x++)
				{
					if (bitMatrix.get(x, y))
					{
						pixels[y * GlobalData.QR_WIDTH + x] = 0xff000000;
					}
					else
					{
						pixels[y * GlobalData.QR_WIDTH + x] = 0xffffffff;
					}
				}
			}
			//生成二维码图片的格式，使用ARGB_8888
			Bitmap bitmap = Bitmap.createBitmap(GlobalData.QR_WIDTH, GlobalData.QR_HEIGHT, Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, GlobalData.QR_WIDTH, 0, 0, GlobalData.QR_WIDTH, GlobalData.QR_HEIGHT);
			saveImage(bitmap);
			//显示到一个ImageView上面

			view.setImageBitmap(bitmap);
		} catch (WriterException e)
		{
		}
	}

	public void saveImage(Bitmap bmp)
	{
		File appDir = new File(Environment.getExternalStorageDirectory(), "FindIt");
		if (!appDir.exists())
		{
			appDir.mkdir();
		}
		String fileName = editTextItemName.getText().toString() + ".jpg";
		Log.i("FindIt", fileName);
		File file = new File(appDir, fileName);
		try
		{
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10) hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	private void showQRCodeDialog(DialogPlus.Gravity gravity, String string) {
		Holder holder;
		holder = new ViewHolder(R.layout.qrcode_dialog);

		OnClickListener clickListener = new OnClickListener() {
			@Override
			public void onClick(DialogPlus dialog, View view) {
				switch (view.getId()) {
				}
				dialog.dismiss();
				ObjectActivity.this.finish();
			}
		};

		OnDismissListener dismissListener = new OnDismissListener() {
			@Override
			public void onDismiss(DialogPlus dialog) {

			}
		};

		OnCancelListener cancelListener = new OnCancelListener() {
			@Override
			public void onCancel(DialogPlus dialog) {

			}
		};

		final DialogPlus dialog = new DialogPlus.Builder(this)
				.setContentHolder(holder)
				.setCancelable(true)
				.setGravity(gravity)
				.setOnClickListener(clickListener)
				.setOnDismissListener(dismissListener)
				.setOnCancelListener(cancelListener)
				.create();

		ImageView view_qrcode = (ImageView) dialog.getHolderView().findViewById(R.id.imageview_qrcode);
		createQRImage(string, view_qrcode);

		Button btn = (Button) dialog.getHolderView().findViewById(R.id.button_qrcode);
		btn.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				ObjectActivity.this.finish();
			}
		});

		dialog.show();
	}
}
